'''
Created on Apr 14, 2011

@author: yc30v1m
'''
from library.AutoLoad import AutoLoad
from logging import getLogger
import re

log = getLogger(__name__)

class TestCase(object):
    '''
    classdocs
    '''
    tcid = None
    tcScript = ''
    log = None
    testCase = None
    testCaseNotes = []
    _testCaseNotes = None
    testCaseStatus = 'PASS'
    count=0
    
    #TODO Put a link to Broadcast Results
    
    @staticmethod
    def supportedExecutionTypes(tcTypes):
        """
        Mandatory method in every inherited class
        This Method has the Type of Execution it handles
        Such as CountValidation / Api Validation / Pws etc
        """
        return False

    def __init__(self, testCaseAsDict):
        self.testCase = testCaseAsDict
        self.tcid = self.getTestCaseOption("TESTCASE_ID")
        del self.testCaseNotes[:]
        self.executeTestSteps()
    
    def executeTestSteps(self):
        pass
        
    def getTestCaseOption(self, option):
        return self.testCase[option]
        
        
    def getOptionsFromSection(self,scriptSection,scriptOption):
        return self.tcScript.getOptionsFromSection("SECTION2", "query")
    
    def testCaseResults(self):
        self.testCaseResult(self.testCaseStatus)
    
    def testCaseResult(self, result):
        report = AutoLoad.ClassAsObject('library.testresults.Reporter')
        self.notesToString()
        report.setTestCaseResult(self.tcid, result, self._testCaseNotes)
        
    ''' 
    errors occured in every row of file will be converted to
    single line before sending to report broadcasting
    '''
    def notesToString(self):
        self._testCaseNotes = ", ".join(self.testCaseNotes)
        
        
    def addTestExecutionNotes(self,notes):
        self.testCaseNotes.append(notes)

    def testCaseFailedOnce(self):
        self.testCaseStatus = 'FAIL'
        
    def replaceQueryWithValue(self, query,replacmentText , replacementValue):
        try:
            newQuery = query.replace(replacmentText,replacementValue)
            return newQuery
        except:
            log.critical("Unable to perform Replacement in Query"  + str(query))
            
    '''
     Replace the multiple values based on finding the keys in dictionary
    '''
            
    def multipleReplace(self,query,replacementValue):
#        repValues=self.mergeValues(replacmentText, replacementValue)
        repValues=replacementValue

        try:
            regex = re.compile("(%s)" % "|".join(map(re.escape, repValues.keys())))
            return regex.sub(lambda mo: repValues[mo.string[mo.start():mo.end()]],query)
        except:
            log.critical("Unable to perform Replacement in Query"  + str(query))
            
    def mergeValues(self,replacmentText, replacementValue):
        replaceValues={}
        for i in range(len(replacmentText)):
            replaceValues[replacmentText[i]]=replacementValue[i]
        return replaceValues
             
    def runQuery(self,query,dbName):
        try:
            connector = AutoLoad.ClassAsObject('library.mappers.DBQueryConnectionMapper')
            #connector.execute(dbName,query)
            #query = "select gift_wrap_desc from gift_wrap where gift_wrap_id in (102)"
            connector.execute(dbName,query)
            return connector.getCurrentRowValuesAsList()
        except:
            log.critical("Unable to run query")
            
    def runSingleRowQuery(self,query,dbName):
        try:
            connector = AutoLoad.ClassAsObject('library.mappers.DBQueryConnectionMapper')
            connector.execute(dbName,query)
            connector.rewind()
            return connector.getCurrentRowAsDict()
        except:
            AutoLoad.logExceptionInfo(10)
            log.critical("Unable to run query")
        